package com.material.web.controller.common;

import com.material.common.config.FileConfig;
import com.material.common.config.RuoYiConfig;
import com.material.common.constant.Constants;
import com.material.common.core.domain.AjaxResult;
import com.material.common.utils.DateUtils;
import com.material.common.utils.OssClientUtil;
import com.material.common.utils.StringUtils;
import com.material.common.utils.file.FileUploadUtils;
import com.material.common.utils.file.FileUtils;
import com.material.framework.config.ServerConfig;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 通用请求处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/common")
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    private static final String FILE_DELIMETER = ",";
    @Autowired
    private FileConfig fileConfig;

    private List<String> imageMimeTypes = Arrays.asList(
            "image/jpeg", "image/png", "image/gif", "image/bmp", "image/tiff"
    );


    private List<String> imageFileExtensions = Arrays.asList(
            "jpg", "jpeg", "png", "gif", "bmp", "tiff"
    );

    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload1")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return AjaxResult.error("文件为空，请选择文件");
        }
        // 上传并返回新文件名称
        try {
            String datePath = DateUtils.datePath();
            String originalFilename = file.getOriginalFilename();
            String fileExtension = getFileExtension(originalFilename);
            String fileName = datePath + "/" + DateUtils.dateTimeNow() + "." +fileExtension;
            String url = null;
            boolean image = isImage(file);
            if(image){
                url = OssClientUtil.uploadImage(fileName, file.getInputStream());
            }else{
                url = OssClientUtil.uploadFile(fileName, file.getInputStream());
            }

            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (IOException e) {
            return AjaxResult.error("文件上传失败");
        }
    }

    @PostMapping("/uploadFile")
    public AjaxResult uploadImageFile(MultipartFile file) throws Exception{
        try {
            String profile = RuoYiConfig.getProfile();
            String basePath = "/goodsDetail/" + DateUtils.datePath();
            String uploadDir = profile +basePath;
            File uploadPath = new File(uploadDir);
            if (!uploadPath.exists()) {
                uploadPath.mkdirs(); // 如果目录不存在，创建目录
            }

            String time = System.currentTimeMillis() + "";
            // 保存文件
            String fileName = time + "_" + file.getOriginalFilename();
            String filePath = uploadDir + "/" +fileName;
            file.transferTo(new File(filePath));

            String fileUrl = fileConfig.getBaseUrl() + basePath + "/" + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileUrl);
            return ajax;
        } catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    private boolean isImage(MultipartFile file){
        // 获取文件的 MIME 类型
        String contentType = file.getContentType();
        // 获取文件的扩展名
        String fileExtension = getFileExtension(file.getOriginalFilename());
        // 判断文件是否为图片
        if (imageMimeTypes.contains(contentType) && imageFileExtensions.contains(fileExtension)) {
            return true;
        } else {
            return false;
        }
    }

    private  String getFileExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "";
        }

        // 获取文件名中最后一个点（.）的位置
        int lastIndexOfDot = fileName.lastIndexOf('.');

        // 如果没有点，或者点在文件名的开头（隐藏文件），则没有扩展名
        if (lastIndexOfDot == -1 || lastIndexOfDot == 0) {
            return "";
        }

        // 返回点后面的字符串作为扩展名
        return fileName.substring(lastIndexOfDot + 1);
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
}
